package JUC_stady;

import java.util.concurrent.*;

/**
 * Project: tobe-better-coder
 * Package: JUC_stady
 * FutureTask有一个很大的问题，当你需要获取异步的返回结果的时候，get()会造成线程阻塞，可以用isDone()来进行轮询判断，但是这样会造成CPU无谓的性能损耗
 *
 * @author : Mr.xu
 * @date : 2023/2/24 0:17
 */
public class TestFuture {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        FutureTask task1 = new FutureTask(() -> {
            System.out.println(Thread.currentThread().getName() + "正在执行任务一");
            Thread.sleep(5000);
            return 1;
        });
        threadPool.submit(task1);
        /**
         * 尽量不要用这种new方法创建线程，很消耗资源，建议用线程池
         */
//        Thread thread = new Thread(task1);
//        thread.start();

        System.out.println(Thread.currentThread().getName() + "正在执行主任务");
//        System.out.println(task1.get());

        while (true) {
            if (task1.isDone()) {
                System.out.println("任务完成，返回结果" + task1.get());
                break;
            } else {
                Thread.sleep(500);
                System.out.println(Thread.currentThread().getName() + "任务尚未完成");
            }
        }

    }

}

class Thread_Callable implements Callable {

    @Override
    public Object call() throws Exception {
        System.out.println("进入 call 方法，执行任务");
        return "hello call";
    }
}